package com.lmy.springboot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行前被调用，大部分拦截业务都在此执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取访问的uri
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        log.info("preHandle拦截到的请求uri={}", requestURI);
        log.info("preHandle拦截到的请求url={}", requestURL.toString());
        //进行登录校验，获取session
        Object user = request.getSession().getAttribute("loginUser");
        if (null != user) { //说明该用户成功登录过
            return true;
        } else {    //没有成功登录，拦截请求
            //重新返回到登录页面
            request.setAttribute("msg", "未登录/请登录");
            //转发到登录页面,get请求
            request.getRequestDispatcher("/").forward(request, response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle()被执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion()被执行");
    }
}
